package org.newlucene.suggest;

public class Util
{
    public static int getMin (int l) 
    {
    	return l >= 5 ? 3 : 2;
    }


    public static int getMax (int l) 
    {
    	return l - 1;    	
    }

    public static String getAllGrams(String word)
    {
    	word = word.toLowerCase();
    	StringBuilder sb = new StringBuilder();
    	int minLen = getMin(word.length());
    	int maxLen = getMax(word.length());
    	for (int len = minLen; len <= maxLen; len++)
    	{
    		String[] grams = formGrams(word, len);
    		sb.append("start_").append(grams[0]).append(" ");
    		for (String gram : grams)
    		{
    			sb.append("gram_").append(gram).append(" ");
    		}
    		sb.append("end_").append(grams[grams.length -1]).append(" ");
    	}
    	return sb.toString();
    }

	/**
	 * Form all ngrams for a given word.
	 * @param word the word to parse
	 * @param gramLen the ngram length e.g. 3
	 * @return an array of all ngrams in the word and note that duplicates are not removed
	 */
	private static String[] formGrams (String word, int gramLen) 
	{
	    int len = word.length();
	    String[] res = new String[len - gramLen + 1];
	    for (int i = 0; i < len - gramLen + 1; i++) 
	    {
	        res[i] = word.substring(i, i + gramLen);
	    }
	    
	    return res;
	}
	
	public static void main(String[] args)
	{
		String word = "rotating";
		System.out.println(getAllGrams(word));
	}
}
